package com.wufeng.controller;

import com.wufeng.dto.ChatRecordDto;
import com.wufeng.dto.KnowledgeUserDto;
import com.wufeng.dto.R;
import com.wufeng.entity.ChatRecord;
import com.wufeng.entity.Knowledge;
import com.wufeng.entity.User;
import com.wufeng.service.ChatRecordService;
import com.wufeng.service.UserService;
import com.wufeng.ws.ChatEndPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: WuFeng
 * @date: 2023/4/13 15:15
 * @desc:
 */
@RestController
@RequestMapping("/chatrecord")
public class ChatRecordController {


    @Autowired
    private ChatEndPoint chatEndPoint;

    @Autowired
    private ChatRecordService chatRecordService;

    @Autowired
    private UserService userService;

    /**
     * 获取在线咨询师列表
     *
     * @return
     */
    @GetMapping("/getOnlineUser")
    public R getOnlineUser() {
        return R.ok();
    }

    /**
     * 根据条件查询记录
     *
     * @param params
     * @return
     */
    @PostMapping("/getChatRecordByCondition")
    public R getChatRecordByCondition(@RequestBody Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        if (pageIndex == null || pageSize == null) {
            pageIndex = 1;
            pageSize = 5;
        }

        HashMap<String, Object> map = new HashMap<>();
        List<User> userList = userService.getUserListByUserName((String) params.get("username"));

        List<Integer> userIds = userList.stream().map(user -> user.getUserid()).collect(Collectors.toList());
        String message = (String) params.get("message");

        List<ChatRecordDto> recordList = chatRecordService.getChatRecordByCondition(userIds, message, pageIndex, pageSize);

        map.put("recordList", recordList);
        return R.ok(map);
    }


    /**
     * 根据条件查询记录条数
     *
     * @param params
     * @return
     */
    @PostMapping("/countChatRecordByCondition")
    public R countChatRecordByCondition(@RequestBody Map<String, Object> params) {

        HashMap<String, Object> map = new HashMap<>();
        List<User> userList = userService.getUserListByUserName((String) params.get("username"));

        List<Integer> userIds = userList.stream().map(user -> user.getUserid()).collect(Collectors.toList());
        String message = (String) params.get("message");

        Integer count = chatRecordService.countChatRecordByCondition(userIds, message);

        map.put("total", count);
        return R.ok(map);
    }


    @PostMapping("/deleteRecordById")
    public R deleteRecordById(Integer chatId) {
        boolean b = chatRecordService.removeById(chatId);
        return b ? R.ok("删除成功！") : R.error("删除失败！");
    }
}
